package com.gdip.service.impl;


import com.gdip.common.dtos.ResponseResult;
import com.gdip.common.enums.AppHttpCodeEnum;
import com.gdip.dto.UserDTO;
import com.gdip.mapper.SchoolClassMapper;
import com.gdip.mapper.UserMapper;
import com.gdip.po.SchoolClass;
import com.gdip.po.UserPo;
import com.gdip.service.UserService;
import com.gdip.vo.UserVO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Resource
    UserMapper userMapper;
    @Autowired
    SchoolClassMapper schoolClassMapper;


    @Override
    public ResponseResult register(UserDTO userDTO) {

        UserPo newUser = new UserPo();
        BeanUtils.copyProperties(userDTO,newUser);
        // MD5算法加密
        newUser.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        System.out.println(newUser);

        int insertedRows = userMapper.insertUser(newUser);

        // 根据插入操作的结果返回不同的响应
        if (insertedRows > 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult login(UserDTO userDTO, HttpSession session) {
        String digest = DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes());

        UserPo byUsername = userMapper.findByUsername(userDTO.getUsername());

        if (byUsername!=null&&digest.equals(byUsername.getPassword())){
            session.setAttribute("userId",byUsername.getId());
            System.out.println(session.getAttribute("userId"));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    // 按账号模糊查询
    @Override
    public ResponseResult getUserByLike(String username) {
        // 参数合规性判断
        if(username.trim().isEmpty() || username.length() > 20){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }else{
            List<UserPo> list = userMapper.getUserByUsernameLike(username);
            return ResponseResult.okResult(list);
        }
    }

    // 管理员操作-批量设置用户权限
    @Override
    @Transactional  // 添加事务注解
    public ResponseResult set_permissions(List<UserPo> list) {
        if(list.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }else{
            try{
                list.forEach(user -> {
                    int count = userMapper.updateUser(user);
                });
            }catch (Exception e) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    //查看某个学院
    @Override
    public ResponseResult getSchoolClassById(int id) {
        String schoolClass = schoolClassMapper.getSchoolClassById(id);
        if (schoolClass != null) {
            return ResponseResult.okResult(schoolClass);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
    }

    @Override
    public ResponseResult getUserData(Integer userId) {
        UserPo byId = userMapper.findById(userId);

        String schoolClassById = schoolClassMapper.getSchoolClassById(byId.getUClass());

        UserVO userVO = new UserVO();
        userVO.setUsername(byId.getUsername());
        userVO.setUClass(schoolClassById);
        userVO.setPermissions(byId.getPermissions());

        userVO.setRole(permissionTORole(byId.getPermissions()));


        if (byId != null){
            return ResponseResult.okResult(userVO);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult getRoles() {

        List<UserPo> all = userMapper.findAll();

        List<UserVO> userVOS = new ArrayList<>();
        for (UserPo userPo : all) {
            UserVO userVO = new UserVO();
            userVO.setUsername(userPo.getUsername());
            userVO.setRole(permissionTORole(userPo.getPermissions()));

            userVOS.add(userVO);
        }
        return ResponseResult.okResult(userVOS);
    }

    @Override
    public ResponseResult searchRoles(String username, String role) {
        List<UserPo> userPos = userMapper.findByUsernameAndPermissions(username, Integer.valueOf(role));


        List<UserVO> userVOS = new ArrayList<>();
        for (UserPo userPo : userPos) {
            UserVO userVO = new UserVO();
            userVO.setUsername(userPo.getUsername());
            userVO.setRole(permissionTORole(userPo.getPermissions()));

            userVOS.add(userVO);
        }
        return ResponseResult.okResult(userVOS);
    }

    @Override
    public ResponseResult updateRole(UserDTO userDTO) {
        UserPo byUsername = userMapper.findByUsername(userDTO.getUsername());

        byUsername.setPermissions(roleToPermission(userDTO.getRole()));

        int i = userMapper.updateUser(byUsername);

        if (i>0){
            return ResponseResult.okResult(null);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }


    public String permissionTORole(Integer id){
        String role;
        // 根据permissions赋值不同的role
        switch (id) {
            case 1:
                role = "管理员";
                break;
            case 2:
                role = "学校领导";
                break;
            case 3:
                role = "部门领导";
                break;
            case 4:
                role = "教师";
                break;
            case 5:
                role = "学生";
                break;
            default:
                role = "未知2";
                break;
        }

        return role;
    }

    public Integer roleToPermission(String role) {
        Integer permissionId;
        // 根据角色名称赋值不同的权限ID
        switch (role) {
            case "管理员":
                permissionId = 1;
                break;
            case "学校领导":
                permissionId = 2;
                break;
            case "部门领导":
                permissionId = 3;
                break;
            case "教师":
                permissionId = 4;
                break;
            case "学生":
                permissionId = 5;
                break;
            default:
                permissionId = null; // 或者某个表示未知的默认值
                break;
        }

        return permissionId;
    }

}

